<?php
	
	namespace Aspic\Database\Mysql;
	use Aspic\Database as Db;
	
	/**
	* Mysql Database Table Class
	* 
	* @use SqlUtil
	* 
	* @Author Mallory Dessaintes <mdessaintes@gmail.com>
	* @version 1.0
	*/
	class Table extends Db\AbstractTable {
		
		public function updateTable($addNewColumns = true, $dropOldColumns = true, $updateColumnsTypes = true) {
			if(is_null($this->getDataModel())) {
				throw new A\Exception('Method "'.__METHOD__.'" could not be called because no DataModel has been set');
			}
			
			$cb = new A\CodeBuilder;
			
			$dataModelColumns = $this->getDataModel()->getCols();
			$dataModelColumnsNames = A\UArray::getLinesIndex($dataModelColumns, 'name');
			
			$tableColumns = $this->fetchTableColumns();
			$tableColumnsNames = A\UArray::getLinesIndex($tableColumns, 'name');
			
			if ($addNewColumns) {
				// Adding columns to DB
				foreach ($dataModelColumns as $col) {
					if (!in_array($col['name'], $tableColumnsNames)) {
						$cb->clear();
						$cb->next('ALTER TABLE "'.$this->getTableName().'"');
						$cb->nl('ADD '.$this->util()->getColDefinition($col));
						
						$this->_db->query($cb->out());
					}
				}
			}
			
			if ($dropOldColumns) {
				// Droping columns from DB
				foreach ($tableColumns as $col) {
					if (!in_array($col['name'], $dataModelColumnsNames)) {
						$cb->clear();
						$cb->next('ALTER TABLE "'.$this->getTableName().'"');
						$cb->nl('DROP COLUMN "'.$col['name'].'"');

						$this->_db->query($cb->out());
					}
				}
			}
			
			if ($updateColumnsTypes) {
				$commonColumns = array_intersect($tableColumnsNames, $dataModelColumnsNames);
				
				foreach($commonColumns as $colName) {
					$dataModelCol = $dataModelColumns[$colName];
					$tableCol = A\UArray::inLinesSearch($tableColumns, $colName, 'name');
					
					if ($this->util()->getSqlType($dataModelCol['type'], $dataModelCol['typeLength']) != $tableCol['type']) {
						$cb->clear();
						$cb->next('ALTER TABLE "'.$this->getTableName().'"');
						$cb->nl('MODIFY '.$this->util()->getColDefinition($dataModelCol));
						
						$this->_db->query($cb->out());
					}
				}
			}
			
		}
		
	}	
	
?>